package view.components;

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;

import javax.swing.*;

import view.Observer;

import controller.Controller;

/**
 * This class creates a basic workspace in each tab It also manages all tabs If
 * a tab(workspace) is switched, it relates the selected tab with command input
 * 
 * @author Yin, Alex
 */
@SuppressWarnings("serial")
public class SLogoTabManager extends JTabbedPane implements MouseListener {

    private Controller myController;

    public SLogoTabManager(String tabName, Controller controller)
            throws IOException {
        myController = controller;
        this.addTab(tabName, myController);
        this.setVisible(true);
    }

    /**
     * 
     * @return currently selected turtle canvas
     */
    public Observer getObserver() {
        return ((SLogoCanvas) getSelectedComponent()).getObserver();
    }

    /**
     * Turtle Canvas
     * 
     * @return the selected TurtleCanvas
     */
    public TurtleCanvas getTurtleCanvas() {
        return ((SLogoCanvas) getSelectedComponent()).getTurtleCanvas();
    }

    /**
     * Set tab size as preferred size Notice: it will change sizes for all tabs
     * simultaneously
     */
    public void setSize(Dimension dimension) {
        setPreferredSize(dimension);
    }

    /**
     * Add new tab(workspace) to GUI
     * 
     * @param tabName
     * @param controller
     * @throws IOException
     */
    public void addTab(String tabName, Controller controller)
            throws IOException {
        SLogoCanvas canvas = new SLogoCanvas(controller, this);
        CloseTabIcon icon = new CloseTabIcon(new ImageIcon());
        addTab(tabName, icon, canvas);
    }

    /**
     * 
     * @return user command from typing
     */
    public String getInput() {
        SLogoCanvas canvas = (SLogoCanvas) getSelectedComponent();
        return canvas.getInput();
    }

    /**
     * Remove tab(workspace) from GUI
     */
    public void removeTab() {
        this.remove(this.getSelectedComponent());
    }

    @Override
    public void mouseClicked(MouseEvent e) {

        int tabNumber = getUI().tabForCoordinate(this, e.getX(), e.getY());
        if (tabNumber < 0) {
            return;
        }
        Rectangle rect = ((CloseTabIcon) getIconAt(tabNumber)).getBounds();
        if (rect.contains(e.getX(), e.getY())) {
            removeTabAt(tabNumber);
        }
    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

}
